/**
 * @author: giscafer ,https://github.com/giscafer
 * @date: 2018-12-03 17:23:03
 * @description:
 */

var mongoose = require('mongoose');

var Products = mongoose.model('Products');
var User = mongoose.model('User');
var Feedback = mongoose.model('Feedback');
/*处理时间*/
var Moment = require('moment');
// 首页
exports.admin = function (req, res) {
	var isSuper = '普通管理员';
	if (req.session.user.status === '2') {
		isSuper = '超级管理员';
	} else if (req.session.user.status == '-1') {
		// 访客
		isSuper = false;
		req.session.user = null;
		res.redirect('/login');
		return;
	}
	res.render('admin/index', { username: req.session.user.username, isSuper: isSuper });
};

// 添加产品
exports.add_products = function (req, res) {
	/* var title = req.body.title;
	var supplyTime = req.body.time;
	var waybillId = req.body.waybillId;
	var from = req.body.from;
	var category = req.body.category;
	var description = req.body.description;
	var productNo = req.body.productNo;
	var price = req.body.price;
	var order = req.body.order;
	var refPrice = req.body.refPrice;
	var shopPrice = req.body.shopPrice || 0;
	var content = req.body.content;
	var status = req.body.status; */
	var createTime = new Date().toISOString();
	let {
		title,
		waybillId,
		supplyTime,
		from,
		price = 0,
		refPrice = 0,
		shopPrice = 0,
		order = 1,
		time = createTime,
		category,
		status,
		productNo,
		description,
		content,
	} = req.body;

	var createTime = new Date().toISOString();
	var data = new Products({
		title,
		waybillId,
		supplyTime: time,
		from,
		price,
		order,
		refPrice,
		shopPrice,
		time,
		category,
		status,
		productNo,
		description,
		content,
	});
	data.save(function (err) {
		if (err) {
			res.json({ status: 'error' });
		} else {
			res.json({ status: 'success' });
		}
	});
};

// 编辑产品详情
exports.edit_products = function (req, res) {
	var id = req.body.id;
	var title = req.body.title;
	var supplyTime = req.body.time;
	var waybillId = req.body.waybillId;
	var from = req.body.from;
	var price = req.body.price;
	var refPrice = req.body.refPrice;
	var shopPrice = req.body.shopPrice || 0;
	var order = req.body.order;
	var category = req.body.category;
	var description = req.body.description;
	var productNo = req.body.productNo;
	var status = req.body.status;
	var content = req.body.content;

	Products.findOne({ _id: id }, function (err, doc) {
		if (err) {
			res.json({ status: 'error' });
		} else {
			Object.assign(doc, {
				title: title,
				waybillId: waybillId,
				supplyTime: supplyTime,
				from: from,
				price: price,
				order: order || 1,
				refPrice: refPrice,
				shopPrice: shopPrice,
				category: category,
				productNo: productNo,
				description: description,
				status: status,
				content: content,
			});
			doc.save(function (re, doc) {
				if (err) {
					res.json({ status: 'error' });
				} else {
					res.json({ status: 'success' });
				}
			});
		}
	});
};
// 获取产品详情
exports.get_products_detail = function (req, res) {
	var id = req.body.id;
	Products.findOne({ _id: id }, function (err, doc) {
		if (err) {
			res.json({ status: 'error' });
		} else {
			res.json({ status: 'success', data: doc.content, id: doc._id, info: doc });
		}
	});
};

// 删除一个产品
exports.del_one = function (req, res) {
	var id = req.body.id;
	Products.remove({ _id: id }, function (err, doc) {
		if (err) {
			res.json({ status: 'error' });
		} else {
			res.json({ status: 'success' });
		}
	});
};

// 进入登录页面
exports.login = function (req, res) {
	res.render('admin/login');
};
// 进入注册页面
exports.register = function (req, res) {
	res.render('admin/register');
};

// post登录信息，校验
exports.checkUser = function (req, res) {
	var username = req.body.username;
	var password = req.body.password;
	var captcha = req.body.captcha || '';

	captcha = captcha.toLocaleLowerCase();
	if (req.session.captcha) {
		req.session.captcha = req.session.captcha.toLocaleLowerCase();
	}
	if (captcha != req.session.captcha) {
		console.log('captcha error');
		res.json({ status: 'captcha error' });
	} else {
		// 验证码正确
		User.findOne({ username: username }, function (err, doc) {
			if (err) {
				console.log('error');
				res.json({ status: 'error' });
			} else if (doc == null) {
				console.log('not exist');
				res.json({ status: 'not exist' });
			} else if (doc.status === '0') {
				// 如果是刚注册的用户，还未授权无法登陆。
				console.log('unchecked');
				res.json({ status: 'unchecked' });
			} else if (doc.password === password) {
				if (doc.status === '-1') {
					// 访客
					console.log('visitor');
					doc.isSuper = false;
					req.session.user = doc;
					return res.json({ status: 'visitor' });
				}
				console.log('success');
				// 登录成功，将user保存到session中
				req.session.user = doc;
				res.json({ status: 'success' });
			} else {
				console.log('password error');
				res.json({ status: 'password error' });
			}
		});
	}
};
// 用户登出操作
exports.logout = function (req, res) {
	req.session.user = null;
	res.redirect('/login');
};

// 添加管理员
exports.post_register = function (req, res) {
	var username = req.body.username;
	var password = req.body.password;
	var realname = req.body.realname;
	var phone = req.body.phone;
	var captcha = req.body.captcha;

	if (captcha != req.session.captcha) {
		console.log('captcha error');
		res.json({ status: 'captcha error' });
	} else {
		// 验证码正确
		var user = new User({
			username: username,
			password: password,
			realname: realname,
			phone: phone,
			status: '0',
		});
		User.findOne({ username: username }, function (err, doc) {
			if (err) {
				res.json({ status: 'error' });
			} else if (doc) {
				res.json({ status: 'user exist' });
			} else {
				User.create(user, function (err, doc) {
					if (err) {
						res.json({ status: 'error' });
					}
					res.json({ status: 'success' });
				});
			}
		});
	}
};

// 确定授权
exports.authorize = function (req, res) {
	if (req.session.user.status != '2') {
		// 0表示普通用户，1表示已授权普通用户，2表示高级用户
		res.json({ status: 'noRight' });
	} else {
		var id = req.body.id;
		User.findOne({ _id: id }, function (err, doc) {
			if (err) {
				res.json({ status: 'error' });
			} else {
				doc.status = '1';
				// 修改后必须的保存
				doc.save(function (err) {
					if (err) {
						res.json({ status: 'error' });
					} else {
						res.json({ status: 'success' });
					}
				});
			}
		});
	}
};

// 添加管理员（用于postMan测试，可删除）
exports.add_admin = function (req, res) {
	if (req.session.user.status != '2') {
		// 0表示普通用户，1表示已授权普通用户，2表示高级用户
		res.json({ status: 'noRight' });
	} else {
		// 超级管理员有权利删除操作
		var username = req.body.username;
		var password = req.body.password;
		var realname = req.body.realname;
		var phone = req.body.phone;

		var user = new User({
			username: username,
			password: password,
			realname: realname,
			phone: phone,
			status: '1',
		});

		User.findOne({ username: username }, function (err, doc) {
			if (err) {
				res.json({ status: 'error' });
			} else if (doc) {
				res.json({ status: 'user_exist' });
			} else {
				User.create(user, function (err, doc) {
					if (err) {
						res.json({ status: 'error' });
					}
					res.json({ status: 'success' });
				});
			}
		});
	}
};
// 分页获取离职公示
exports.get_users = function (req, res) {
	var curr = req.body.curr;
	// 每页大小为10
	var query = User.find({});
	query.skip((curr - 1) * 10);
	query.limit(10);
	// 按照id添加的顺序倒序排列
	query.sort({ _id: -1 });
	// 计算分页数据
	query.exec(function (err, rs) {
		if (err) {
			res.send(err);
		} else {
			// 计算数据总数
			User.find(function (err, result) {
				if (result.length % 10 > 0) {
					pages = result.length / 10 + 1;
				} else {
					pages = result.length / 10;
				}
				jsonArray = { data: rs, pages: pages };
				res.json(jsonArray);
			});
		}
	});
};
// 删除一个管理员
exports.user_del = function (req, res) {
	if (req.session.user.status != '2') {
		// 0表示普通用户，1表示已授权普通用户，2表示高级用户
		res.json({ status: 'noRight' });
	} else {
		var id = req.body.id;
		User.remove({ _id: id }, function (err, doc) {
			if (err) {
				res.json({ status: 'error' });
			} else {
				res.json({ status: 'success' });
			}
		});
	}
};

// 分页获取离职公示
exports.get_feedbacks = function (req, res) {
	var curr = req.body.curr;
	// 每页大小为10
	var query = Feedback.find({});
	query.skip((curr - 1) * 10);
	query.limit(10);
	// 按照id添加的顺序倒序排列
	query.sort({ _id: -1 });
	// 计算分页数据
	query.exec(function (err, rs) {
		if (err) {
			res.send(err);
		} else {
			// 计算数据总数
			Feedback.find(function (err, result) {
				if (result.length % 10 > 0) {
					pages = result.length / 10 + 1;
				} else {
					pages = result.length / 10;
				}
				jsonArray = { data: rs, pages: pages };
				res.json(jsonArray);
			});
		}
	});
};

// 通过_id反馈信息
exports.deal_feedbacks = function (req, res) {
	var id = req.body.id;
	Feedback.findOne({ _id: id }, function (err, doc) {
		if (err) {
			res.json({ status: 'error' });
		} else {
			doc.status = '1';
			// 修改后必须的保存
			doc.save(function (err) {
				if (err) {
					res.json({ status: 'error' });
				} else {
					res.json({ status: 'success' });
				}
			});
		}
	});
};

// 校验后台是否有未处理反馈信息
exports.check_feedbacks = function (req, res) {
	// 计算未处理反馈信息条数
	Feedback.find({ status: '0' }, function (err, result) {
		if (err) {
			res.json({ status: 'error' });
		} else if (result.length === 0) {
			res.json({ status: 'error' });
		} else {
			res.json({ status: 'success', size: result.length });
		}
	});
};

// 分页获取产品信息
exports.get_products = function (req, res) {
	var curr = req.body.curr;
	var status = req.body.status;
	var waybillId = req.body.waybillId;
	var category = req.body.category || '';
	var keyword = req.body.keyword || '';
	var pageSize = req.body.pageSize || 10;
	// 每页大小为10
	var query = Products.find({});
	query.skip((curr - 1) * 10);
	query.limit(+pageSize);
	// 按照预约时间添加的顺序倒序排列
	query.sort({ order: -1 });
	var conditions = {};

	if (status !== '') {
		query.where('status', status);
		conditions['status'] = status;
	}
	if (category !== '') {
		query.where('category', category);
		conditions['category'] = category;
	}
	if (waybillId) {
		query.where('waybillId', waybillId);
		conditions['waybillId'] = waybillId;
	}
	if (keyword) {
		query.or([{ title: new RegExp(keyword, 'g') }, { productNo: new RegExp(keyword, 'g') }]);
		conditions['$or'] = [{ title: { $regex: keyword, $options: '$g' } }, { productNo: { $regex: keyword, $options: '$g' } }]
	}
	// 计算分页数据
	query.exec(function (err, rs) {
		if (err) {
			res.send(err);
		} else {
			// 计算数据总数
			Products.find(conditions, function (err, result) {
				pages = Math.ceil(result.length / 10);
				jsonArray = { data: rs, pages: pages, total: result.length };
				res.json(jsonArray);
			});
		}
	});
};

// 通过_id处理产品信息
exports.deal_product = function (req, res) {
	var id = req.body.id;
	var status = req.body.status;
	Products.findOne({ _id: id }, function (err, doc) {
		if (err) {
			res.json({ status: 'error' });
		} else {
			if (!doc) {
				res.json({ status: 'error', msg: '找不到产品' });
				return;
			}
			doc.status = status;
			// 修改后必须的保存
			doc.save(function (err) {
				if (err) {
					res.json({ status: 'error' });
				} else {
					res.json({ status: 'success' });
				}
			});
		}
	});
};
// 通过_id删除产品信息
exports.remove_products = function (req, res) {
	var ids = req.body.id;
	Products.remove({ _id: { $in: ids } }, function (err, doc) {
		if (err) {
			res.json({ status: 'error' });
		} else {
			res.json({ status: 'success' });
		}
	});
};

